package com.sikaryofficial.file.controller;

import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.common.core.utils.file.FileUtils;
import com.sikaryofficial.file.config.FfmpegConfig;
import com.sikaryofficial.file.service.ISysFileService;
import com.sikaryofficial.file.utils.FileUploadUtils;
import com.sikaryofficial.system.api.domain.SysFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件请求处理
 *
 * @author qinjinyuan
 */
@RestController
@RequestMapping("/nocache")
public class SysFileNoCacheController {
    private static final Logger log = LoggerFactory.getLogger(SysFileNoCacheController.class);
    @Autowired
    private ISysFileService sysFileService;
    @Autowired
    private FfmpegConfig ffmpegConfig;

    /**
     * 文件上传请求
     */
    @PostMapping("/upload")
    public R<SysFile> upload(MultipartFile file) {
        return baseUpload(file);
    }

    /**
     * 文章附件文件上传请求
     */
    @PostMapping("/article/upload")
    public R<SysFile> articleUpload(MultipartFile file) {
        return baseUpload(file);
    }

    /**
     * 音频文件上传文件上传请求
     */
    @PostMapping("/audio/upload")
    public R<SysFile> audioUpload(MultipartFile file) {
        try {
            // 上传并返回访问对象
            SysFile sysFile = sysFileService.uploadFileForAudio(file);
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.ok(null,e.getMessage());
        }
    }

    /**
     * 文件上传请求
     */
    @PostMapping("/video/upload")
    public R<SysFile> uploadVideo(MultipartFile file) {
        FileUploadUtils.verifyFileSizeMB(file, ffmpegConfig.getMaxLimitSize());
        try {
            // 上传并返回访问对象
            return R.ok(sysFileService.uploadVideo(file));
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.ok(null, e.getMessage());
        }
    }

    private R<SysFile> baseUpload(MultipartFile file) {
        try {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.ok(null, e.getMessage());
        }
    }
}